#include "user_manager.hpp"
#include <algorithm>

UserManager user_manager;

void UserManager::add_user(int fd) {
    std::lock_guard<std::mutex> lock(mutex);
    fd_to_name[fd] = "anonymous";
}

void UserManager::remove_user(int fd) {
    std::lock_guard<std::mutex> lock(mutex);
    auto it = fd_to_name.find(fd);
    if (it != fd_to_name.end()) {
        name_to_fd.erase(it->second);
        fd_to_name.erase(it);
    }
}

void UserManager::rename_user(int fd, const std::string& name) {
    std::lock_guard<std::mutex> lock(mutex);
    auto old_name = fd_to_name[fd];
    name_to_fd.erase(old_name);
    fd_to_name[fd] = name;
    name_to_fd[name] = fd;
}

std::string UserManager::get_name(int fd) {
    std::lock_guard<std::mutex> lock(mutex);
    auto it = fd_to_name.find(fd);
    return it != fd_to_name.end() ? it->second : "anonymous";
}

int UserManager::get_fd_by_name(const std::string& name) {
    std::lock_guard<std::mutex> lock(mutex);
    auto it = name_to_fd.find(name);
    return it != name_to_fd.end() ? it->second : -1;
}

std::vector<int> UserManager::get_all_fds() {
    std::lock_guard<std::mutex> lock(mutex);
    std::vector<int> fds;
    for (const auto& [fd, _] : fd_to_name) {
        fds.push_back(fd);
    }
    return fds;
}


